import hashlib
import hmac
import json
import time  # for nonce

import requests  # pip install requests

from coin.exchange.base.kr_rest.auth_base import AuthKey


class BitfinexClientBase(object):
  def __init__(self, key_file):
    key = AuthKey.from_file(key_file)
    self.KEY = key.access_key
    self.SECRET = key.secret_key_bytes
    self.BASE_URL = "https://api.bitfinex.com/"

  def _nonce(self):
    """
    Returns a nonce
    Used in authentication
    """
    return str(int(round(time.time() * 1000000)))

  def _headers(self, path, nonce, body):
    signature = "/api/" + path + nonce + body
    h = hmac.new(self.SECRET, signature.encode("utf-8"), hashlib.sha384)
    signature = h.hexdigest()

    return {
        "bfx-nonce": nonce,
        "bfx-apikey": self.KEY,
        "bfx-signature": signature,
        "content-type": "application/json"
    }

  def _query_nocheck(self, path, params=None):
    if params is None:
      params = {}
    nonce = self._nonce()
    rawBody = json.dumps(params)
    assert path.startswith("/")
    path = "v2" + path

    headers = self._headers(path, nonce, rawBody)
    r = requests.post(self.BASE_URL + path, headers=headers, data=rawBody, verify=True)

    if r.status_code == 200:
      return r.json()
    else:
      raise RuntimeError(r)

  def _query(self, path, params=None):
    return self._query_nocheck(path, params=params)


class BitfinexNativePrivateClient(BitfinexClientBase):
  def __init__(self, key_file):
    BitfinexClientBase.__init__(self, key_file)

  def query_wallets(self):
    return self._query("/auth/r/wallets", params=None)

  def query_orders(self):
    return self._query("/auth/r/orders", params=None)

  def query_trades(self, product):
    return self._query("/auth/r/trades/%s/hist" % (product.native_symbol), params=None)

  def query_positions(self):
    return self._query("/auth/r/positions", params=None)
